//
//  YSPTextViewController.swift
//  EmotionIcon
//
//  Created by 朴裕识 on 15/12/29.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

class YSPTextViewController: UIViewController {
    
    private let emoticonPackageModelArray = YSPEmoticonPackageModel.emoticonPackageModelArray
    
    /// cell重用标示
    let reuseIdentifier = "reuseIdentifier"
    
    private var selectedToolBarBtn: UIButton?
    
    let baseTag = 1000
    
    weak var textView: UITextView?
    
    init(textView: UITextView) {
        self.textView = textView
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        prepareUI()
    }
    
    private func prepareUI() {
        view.addSubview(collectionView)
        view.addSubview(toolBar)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : collectionView]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv": collectionView]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : toolBar]))
        
        // 垂直方向
        // 1.collectionView的顶部和父控件的顶部重合
        // 2.collectionView的底部和toolBar的顶部重合
        // 3.toolBar高44
        // 4.toolBar底部和父控件的底部重合
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cb]-0-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cb" : collectionView, "tb": toolBar]))
        setupToolBar()
        setupCollectionView()
    }
    
    /// 设置toolBar
    private func setupToolBar() {
        var items = [UIBarButtonItem]()
        var index = 0
        for emoticonPackageModel in emoticonPackageModelArray {
            let name = emoticonPackageModel.group_name_cn
            // 创建按钮.按钮的文字可以选中和高亮
            let button = UIButton()
            button.setTitle(name, forState: UIControlState.Normal)
            button.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected)
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Highlighted)
            button.sizeToFit()
            
            //添加点击事件
            button.addTarget(self, action: "toolBarDidClicked:", forControlEvents: UIControlEvents.TouchUpInside)
            button.tag = index + baseTag
            
            //如果创建的是最近按钮，直接设置成选中
            if index == 0 {
                toolBarBtnSelectedChanged(button)
            }
            
            let item = UIBarButtonItem(customView: button)
            
            // 添加到数组
            items.append(item)
            
            // 添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            index++
        }
        
        // 移除最后一个弹簧
        items.removeLast()
        
        // 设置toolBar的items
        toolBar.items = items
    }
    
    @objc private func toolBarDidClicked(button: UIButton) {

        let indexPath = NSIndexPath(forItem: 0, inSection: button.tag - baseTag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        toolBarBtnSelectedChanged(button)
    }
    
    private func toolBarBtnSelectedChanged(button: UIButton) {
        //选中状态三部曲
        selectedToolBarBtn?.selected = false
        selectedToolBarBtn = button
        button.selected = true
    }
    
    /// 设置collectionView
    private func setupCollectionView() {
        collectionView.registerClass(YSPCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    
    //MARK: - 懒加载
    private lazy var toolBar = UIToolbar()
    
    private lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: YSPFlowLayout())
        return collectionView
    }()
    
}

extension YSPTextViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        let indexPath = collectionView.indexPathsForVisibleItems()[10]
        let section = indexPath.section + baseTag
        let button = toolBar.viewWithTag(section) as! UIButton
        toolBarBtnSelectedChanged(button)
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

        return emoticonPackageModelArray.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let emoticonPackageModel = emoticonPackageModelArray[section]

        return emoticonPackageModel.emoticonModelArray.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! YSPCollectionViewCell
        let emoticonPackageModel = emoticonPackageModelArray[indexPath.section]
        let emoticonModel = emoticonPackageModel.emoticonModelArray[indexPath.item]
        cell.emoticonModel = emoticonModel
        cell.backgroundColor = UIColor.whiteColor()

        return cell
    }
    //cell的点击事件会被按钮抢走
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

        let emoticonPackageModel = emoticonPackageModelArray[indexPath.section]
        let emoticonModel = emoticonPackageModel.emoticonModelArray[indexPath.item]
        textView?.insertEmoticon(emoticonModel)
        if indexPath.section != 0 {
            YSPEmoticonPackageModel.appendRecentEmoticon(emoticonModel)
            collectionView.reloadSections(NSIndexSet(index: 0))
        }
    }
}

class YSPFlowLayout: UICollectionViewFlowLayout {
    // 覆盖父类的方法
    override func prepareLayout() {
        super.prepareLayout()
        
        //        print("prepareLayout: \(collectionView?.frame)")
        // 设置layout的布局参数
        let itemWidth = collectionView!.frame.width / 7
        let itemHeight = collectionView!.frame.height / 3
        self.itemSize = CGSize(width: itemWidth, height: itemHeight)
        
        // 取消间距
        self.minimumInteritemSpacing = 0
        self.minimumLineSpacing = 0
        
        // 滚动方向
        self.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
    }
}
